package com.tdcy.framework.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

public class ContextUtils {
	private static ApplicationContext applicationContext;

	private static final Logger log = LoggerFactory.getLogger(ContextUtils.class);

	public static void setApplicationContext(
			ApplicationContext applicationContext) {
		synchronized (ContextUtils.class) {
			log.debug("setApplicationContext, notifyAll");
			ContextUtils.applicationContext = applicationContext;
			ContextUtils.class.notifyAll();
		}
	}

	public static ApplicationContext getApplicationContext() {
		synchronized (ContextUtils.class) {
			int num = 100;
			while (applicationContext == null && num > 0) {
				num--;
				try {
					log.debug("getApplicationContext, wait...");
					ContextUtils.class.wait(60000);
					if (applicationContext == null) {
						log.debug("Have been waiting for ApplicationContext to be set for 1 minute",new Exception());
					}
				} catch (InterruptedException ex) {
					log.debug("getApplicationContext, wait interrupted");
				}
			}
			return applicationContext;
		}
	}

	public static <T> T getBean(String name) {
		try {
			return (T)getApplicationContext().getBean(name);
		} catch (Exception e) {
			return null;
		}
	}
	
	public static <T> T getBean(Class clazz) {
		try {
			return (T)getApplicationContext().getBean(clazz);
		} catch (Exception e) {
			return null;
		}
	}
}
